package com.it.interceptor;

import com.alibaba.fastjson.JSON;
import com.it.common.BaseContext;
import com.it.common.PathMatcher;
import com.it.common.R;
import com.it.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        // 1. 白名单直接放行
        if (PathMatcher.check(request.getRequestURI())) {
            return true;
        }

        // 2. 已登录放行
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user != null) {
            BaseContext.setCurrentId(Long.valueOf(((User) user).getUserId()));
            return true;
        }

        // 3. 区分普通页面请求 还是 AJAX/JSON 请求
        boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))
                || request.getHeader("Accept") != null && request.getHeader("Accept").contains("application/json");

        if (isAjax) {
            // 3.1 AJAX：返回 401 + JSON
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(401);
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        } else {
            // 3.2 普通页面：直接重定向
            response.sendRedirect(request.getContextPath() + "/back/page/login/login.html");
        }
        return false;
    }
}